package com.sc.app.security.repo;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.security.service.ValidateCodeType;
import com.sc.security.service.sms.ValidateCodeRepo;
import com.sc.security.validate.code.sms.ValidateCode;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import java.util.concurrent.TimeUnit;

/**
 * @author sc
 * Created on  2018/1/24
 */
@Component
public class ValidateCodeRepoAppImpl implements ValidateCodeRepo{
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void save(ServletWebRequest request, ValidateCode validate, ValidateCodeType validateCodeType) {
        redisTemplate.opsForValue().set(buildKey(request,validateCodeType),validate,30, TimeUnit.MINUTES);
    }

    private String buildKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
        String deviceId = request.getHeader("deviceId");
        if(StringUtils.isBlank(deviceId)){
            throw new RuntimeException("请求中没有deviceID");
        }
        return "code:"+validateCodeType.toString().toLowerCase()+":"+deviceId;
    }

    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType codeType) {
        Object value = redisTemplate.opsForValue().get(buildKey(request,codeType));
        return value==null?null: (ValidateCode) value;
    }

    @Override
    public void remove(ServletWebRequest request, ValidateCodeType codeType) {
        redisTemplate.delete(buildKey(request,codeType));
    }
}
